package com.lightning.web.support.security.identity;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lightning.modules.utils.HashUtils;
import com.lightning.persist.DaoAccessor;
import com.lightning.web.support.security.context.UserDetails;

/**
 * IdentityManager based on Cookie.
 * 
 * @author Michael Liao (askxuefeng@gmail.com)
 */
@Service("cookieIdentityManager")
public class CookieIdentityManager implements IdentityManager {
	private static final String IDENTITY_COOKIE = "_sys_cookie_id_store_";
	private static final Cookie CLEAN_COOKIE;
	private static final long EXPIRES_TIME = 1000L * 3600L * 24L * 365L;
	@Autowired
	private DaoAccessor daoAccessor;
	static {
		CLEAN_COOKIE = new Cookie(IDENTITY_COOKIE, "x");
		CLEAN_COOKIE.setMaxAge(0);
		CLEAN_COOKIE.setPath("/");
	}

	public Identity getIdentity(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;
		String id_cookie = null;
		for (Cookie cookie : cookies) {
			if (IDENTITY_COOKIE.equals(cookie.getName())) {
				id_cookie = cookie.getValue();
				break;
			}
		}
		if (id_cookie == null)
			return null;
		// parse id_cookie: userid_expires_hash
		try {
			String[] ss = id_cookie.split("\\_");
			if (ss.length != 3)
				throw new IllegalArgumentException("Clean invalid cookie.");
			String id = ss[0];
			long expires = Long.parseLong(ss[1]);
			if (System.currentTimeMillis() >= expires)
				throw new IllegalArgumentException("Clean expired cookie.");
			UserDetails user = null;//repository.getUserDao().selectByPrimaryKey(Integer.parseInt(id));
			String hash = calcHash(id, null, expires);
			if (hash.equals(ss[2])) {
				// valid cookie:
				Identity identity = null;//new Identity(user.getId(), user.getClazz(), user.getName(), true, null, null);
				return identity;
			} else {
				throw new IllegalArgumentException("Clean bad cookie.");
			}

		} catch (Exception e) {
			response.addCookie(CLEAN_COOKIE);
			return null;
		}
	}

	public Identity getRequiredIdentity(HttpServletRequest request, HttpServletResponse response) {
		Identity identity = getIdentity(request, response);
		if (identity == null) {

		}
		return identity;
	}

	public void storeIdentity(HttpServletRequest request, HttpServletResponse response, Identity identity) {

		long expires = System.currentTimeMillis() + EXPIRES_TIME;
		StringBuilder sb = new StringBuilder();
		sb.append(identity.getUid()).append('_').append(expires).append('_')
				.append(calcHash(String.valueOf(identity.getUid()), identity.getCookieId(), expires));
		Cookie cookie = new Cookie(IDENTITY_COOKIE, sb.toString());
		cookie.setMaxAge((int) (expires / 1000));
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	public void removeIdentity(HttpServletRequest request, HttpServletResponse response) {
		response.addCookie(CLEAN_COOKIE);
	}

	String calcHash(String id, String password, long expires) {
		return HashUtils.toMD5(id + "_" + password + "_" + expires);
	}

	public static void main(String[] args) {
		UUID uuid = UUID.randomUUID();
		UUID uuid1 = UUID.randomUUID();
		System.out.println(uuid.toString());
		System.out.println(uuid1.toString());
	}
}
